package com.fishery.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fishery.base.entity.*;
import com.fishery.base.entity.vo.FarmingVo;
import com.fishery.base.entity.vo.LeaderPondVo;
import com.fishery.base.service.*;
import com.fishery.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutorService;

/**
 * <p>
 * 池塘前端控制器
 * </p>
 *
 * @author Ghost
 * @since 2021-01-15
 */
@RestController
@RequestMapping("/pond")
@CrossOrigin
@Api(tags = "池塘管理模块")
public class PondController {

	@Autowired
	private PondService pondService;

	@Autowired
	private GermchitPondService germchitPondService;

	@Autowired
	private PondFeedingService pondFeedingService;

	@Autowired
	private ExecutorService threadPool;


	@GetMapping("/getInfo/{baseId}/{size}/{current}")
	@ApiOperation("通过基地ID获取池塘的基本信息（带分页）")
	public Result searchPondInfoWithPage(@PathVariable(name = "baseId", required = true) @ApiParam(required = true, value = "基地ID") String baseId,
										 @PathVariable(name = "size", required = true) @ApiParam(value = "尺寸", required = true) int size,
										 @PathVariable(name = "current", required = true) @ApiParam(value = "页码", required = true) int current) {
		if (StringUtils.isEmpty(baseId)) {
			return Result.error();
		}
		return Result.success().data(pondService.getAllPondInfoWithPage(baseId, size, current));
	}

	@GetMapping("/getOneInfo/{pondId}")
	@ApiOperation("通过池塘ID查询某个池塘的基本信息")
	public Result searchOnePondInfo(@PathVariable(name = "pondId", required = true) @ApiParam(required = true, value = "池塘ID") String pondId) {
		if (StringUtils.isEmpty(pondId)) {
			return Result.error();
		}
		return Result.success().data(pondService.getOnePondInfo(pondId));
	}

	@GetMapping("/getInfo/{baseId}")
	@ApiOperation("通过基地ID获取池塘的基本信息")
	public Result searchAllPondInfo(@PathVariable(name = "baseId", required = true) @ApiParam(required = true, value = "基地ID") String baseId) {
		if (StringUtils.isEmpty(baseId)) {
			return Result.error();
		}
		return Result.success().data(pondService.getAllPondInfo(baseId));
	}


	@PostMapping("/create")
	@ApiOperation("基地创建池塘")
	public Result createPond(@RequestBody @ApiParam(required = true, value = "pond对象") Pond pond) {
		if (pond == null || StringUtils.isEmpty(pond.getBaseId())) {
			return Result.error("创建失败");
		}
		return pondService.save(pond) ? Result.success("创建成功") : Result.error("创建失败");
	}


	@PutMapping
	@ApiOperation("修改池塘信息")
	public Result updatePondInfo(@ApiParam(required = true, value = "池塘对象") Pond pond) {
		if (pond == null || StringUtils.isEmpty(pond.getId())) {
			return Result.error("修改失败");
		}
		return pondService.updateById(pond) ? Result.success("修改成功") : Result.error("修改失败");
	}


	@DeleteMapping("/{pondId}")
	@ApiOperation("通过池塘ID删除池塘")
	@Transactional
	public Result deletePond(@PathVariable(name = "pondId", required = true) @ApiParam(required = true, value = "池塘ID") String pondId) {
		if (StringUtils.isEmpty(pondId)) {
			return Result.error("删除失败");
		}
		// 删除池塘
		threadPool.submit(() -> {
			pondService.removeById(pondId);
		});
		// 构建删除条件
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("pond_id", pondId);
		// 删除对应池塘的养殖信息
		threadPool.submit(() -> {
			germchitPondService.remove(wrapper);
		});
		// 删除对应池塘的喂养信息
		threadPool.submit(() -> {
			pondFeedingService.remove(wrapper);
		});
		return Result.success();
	}


	@PostMapping("/farming")
	@ApiOperation("向池塘投苗")
	public Result farming(@RequestBody @ApiParam(required = true, value = "池塘投苗信息对象") FarmingVo farmingVo) {
		if (farmingVo == null
				|| StringUtils.isEmpty(farmingVo.getGermchitId())
				|| StringUtils.isEmpty(farmingVo.getPondId())
				|| farmingVo.getInputNum() <= 0) {
			return Result.error("投苗失败");
		}
		return germchitPondService.farming(farmingVo) ? Result.success("投苗成功") : Result.error("投苗失败");
	}


	@PutMapping("/catching")
	@ApiOperation("池塘捕捞")
	@Transactional
	public Result catching(@RequestBody @ApiParam(value = "捕捞信息对象") Catch catchVo) {
		if (catchVo == null
				|| StringUtils.isEmpty(catchVo.getPondId())
				|| catchVo.getCatchAmount() < 0
				|| catchVo.getTotalWeight() < 0) {
			return Result.error("捕捞失败");
		}
		return germchitPondService.catching(catchVo) ? Result.success("捕捞成功") : Result.error("捕捞失败");
	}


	@PostMapping("/feeding")
	@ApiOperation("喂养")
	@Transactional
	public Result feeding(@RequestBody @ApiParam(value = "喂养信息对象") PondFeeding pondFeeding) {
		if (pondFeeding == null
				|| StringUtils.isEmpty(pondFeeding.getPondId())
				|| StringUtils.isEmpty(pondFeeding.getSupplyId())
				|| StringUtils.isEmpty(pondFeeding.getOperatorName())
				|| StringUtils.isEmpty(pondFeeding.getSupplyName())
				|| StringUtils.isEmpty(pondFeeding.getSupplyType())
				|| pondFeeding.getFeedingVolume().compareTo(ConstantValue.ZERO) <= 0
				|| StringUtils.isEmpty(pondFeeding.getFarmingId())) {
			return Result.error("喂养失败");
		}
		return pondFeedingService.feeding(pondFeeding) ? Result.success("喂养成功") : Result.error("喂养失败");
	}

	@GetMapping("/feeding/current/{farmingId}/{size}/{current}")
	@ApiOperation("查询当前池塘此次养殖的喂养信息(带分页)")
	public Result getFeedingRecordsOfCurrentFarming(@PathVariable(name = "farmingId", required = true) @ApiParam(required = true, value = "养殖编号") String farmingId,
													@PathVariable(name = "size", required = true) @ApiParam(required = true, value = "尺寸") int size,
													@PathVariable(name = "current", required = true) @ApiParam(required = true, value = "页码") int current) {
		if (StringUtils.isEmpty(farmingId)) {
			return Result.error("查询失败");
		}
		return Result.success().data(pondFeedingService
				.pageFeedingRecordsOfCurrentFarming(farmingId, current, size));
	}

	@GetMapping("/feeding/{baseId}/{size}/{current}")
	@ApiOperation("查询基地喂养记录（包含之前养殖的历史记录，带分页）")
	public Result getBaseFeedingRecords(@PathVariable(name = "baseId", required = true) @ApiParam(required = true, value = "基地Id") String baseId,
										@PathVariable(name = "size", required = true) @ApiParam(required = true, value = "尺寸") int size,
										@PathVariable(name = "current", required = true) @ApiParam(required = true, value = "页码") int current) {
		if (StringUtils.isEmpty(baseId)) {
			return Result.error("查询失败");
		}
		return Result.success().data(pondFeedingService.pageBaseFeedingRecords(baseId, current, size));
	}

	@GetMapping("/feeding/pond/{pondId}/{size}/{current}")
	@ApiOperation("查询获取某个池塘的喂养记录(包含之前养殖的历史记录，带分页)")
	public Result getPondFeedingRecords(@PathVariable(name = "pondId", required = true) @ApiParam(required = true, value = "池塘Id") String pondId,
										@PathVariable(name = "size", required = true) @ApiParam(required = true, value = "尺寸") int size,
										@PathVariable(name = "current", required = true) @ApiParam(required = true, value = "页码") int current) {
		if (StringUtils.isEmpty(pondId)) {
			return Result.error("查询失败");
		}
		return Result.success().data(pondFeedingService.pagePondFeedingRecords(pondId, current, size));
	}

	@DeleteMapping("/feeding/{id}")
	@ApiOperation("通过id删除喂养记录")
	public Result deleteFeedingById(@PathVariable(name = "id", required = true) @ApiParam(required = true, value = "id") String id) {
		if (StringUtils.isEmpty(id)) {
			return Result.error("删除失败");
		}
		return pondFeedingService.removeById(id) ? Result.success("删除成功") : Result.error("删除失败");
	}

	@PutMapping("/feeding")
	@ApiOperation("修改喂养记录")
	@Transactional
	public Result updateFeedingRecord(@RequestBody @ApiParam(value = "投喂信息对象") PondFeeding pondFeeding) {
		if (pondFeeding == null
				|| StringUtils.isEmpty(pondFeeding.getId())
				|| pondFeeding.getFeedingVolume().compareTo(ConstantValue.ZERO) <= 0) {
			return Result.error("修改失败");
		}
		boolean ret = pondFeedingService.updateFeedingRecord(pondFeeding);
		return ret ? Result.success("修改成功") : Result.error("修改失败");
	}

	@GetMapping("/count/{baseId}")
	@ApiOperation("查询基地池塘的总数量、总面积（供领导仓使用）")
	public Result getPondInfo(@PathVariable(name = "baseId", required = true) String baseId) {
		if (StringUtils.isEmpty(baseId)) {
			return Result.error("查询失败");
		}
		LeaderPondVo leaderPondVo = pondService.getPondAmountAndArea(baseId);
		return Result.success().data(leaderPondVo);
	}

	@GetMapping("/feeding/excel/{baseId}")
	@ApiOperation("以Excel文件格式导出基地喂养记录")
	public void getExcelOfFeeding(HttpServletResponse response,
								  @PathVariable(name = "baseId", required = true) @ApiParam(value = "baseId", required = true) String baseId) {
		if (StringUtils.isEmpty(baseId)) {
			return;
		}
		pondFeedingService.getFeedingRecordsByExcel(response, baseId);
	}

}

